<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
    
  
  <link href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="https://cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.css" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.0.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="mask-icon" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0" color="#222">





  <meta name="keywords" content="vps, java, python, golang, springmvc">




  


  <link rel="alternate" href="/atom.xml" title="张恒的网络日志" type="application/atom+xml">






<meta name="keywords" content="java, python, go, 技术, 学习笔记, spring">
<meta property="og:type" content="website">
<meta property="og:title" content="张恒的网络日志">
<meta property="og:url" content="http://blog.gavinzh.com/404.html">
<meta property="og:site_name" content="张恒的网络日志">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-05T08:52:36.912Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="张恒的网络日志">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: true,
    lazyload: true,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.gavinzh.com/404.html">





  <title>Vue的生命周期和前端路由使用 | 张恒的网络日志</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-98061925-1', 'auto');
  ga('send', 'pageview');
</script>





</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">张恒的网络日志</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Zhang Heng's WebSite Blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.gavinzh.com/2020/01/05/Vue-lifecycle-and-front-end-routing-usage/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gavin Zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/5567916">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="张恒的网络日志">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Vue的生命周期和前端路由使用</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-01-05T10:38:00+00:00">2020-01-05</time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/笔记/" itemprop="url" rel="index">
                    <span itemprop="name">笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/01/05/Vue-lifecycle-and-front-end-routing-usage/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2020/01/05/Vue-lifecycle-and-front-end-routing-usage/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2020/01/05/Vue-lifecycle-and-front-end-routing-usage/" class="leancloud_visitors" data-flag-title="Vue的生命周期和前端路由使用">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="0-前言"><a href="#0-前言" class="headerlink" title="0. 前言"></a>0. 前言</h2><p>近半年来，我一直从事一个报表管理系统的开发。管理系统是给人用的，但我们团队并没有前端，所以我就兼任了大部分前端开发工作。在这半年的开发工作中，我学习了一些前端内容，在这里做一个总结并分享给大家。</p>
<p>阅读本文，我假设大家是已了解HTML/CSS和JavaScript中级知识的后端开发。</p>
<a id="more"></a>

<h2 id="1-Vue的生命周期"><a href="#1-Vue的生命周期" class="headerlink" title="1. Vue的生命周期"></a>1. Vue的生命周期</h2><h3 id="1-1-Vue是什么"><a href="#1-1-Vue是什么" class="headerlink" title="1.1 Vue是什么"></a>1.1 Vue是什么</h3><p>对于后端开发人员来讲，写前端最不想写的代码就是数据渲染，因为需要使用JS直接操作DOM树，这个过程极其、并且无聊。而Vue是一套用于构建用户界面的JS框架，它类似于React、AngularJS等框架。在写出一些简单的模板后，它能够帮你自动渲染出页面，并且在数据发生改变后，自动重新渲染页面。</p>
<p>Vue官网：<a href="https://cn.vuejs.org/" target="_blank" rel="noopener">vuejs.org</a></p>
<p>这里是一个简单的demo：</p>
<p><a href="https://codepen.io/jiangmitiao/pen/MWYvgGG" target="_blank" rel="noopener">在线演示</a></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">title</span>&gt;</span><span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"https://cdn.bootcss.com/vue/2.6.10/vue.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"app"</span>&gt;</span></span><br><span class="line">    &#123;&#123; message &#125;&#125;</span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript">	<span class="keyword">var</span> app = <span class="keyword">new</span> Vue(&#123;</span></span><br><span class="line"><span class="actionscript">    el: <span class="string">"#app"</span>,</span></span><br><span class="line">    data: &#123;</span><br><span class="line"><span class="actionscript">      message: <span class="string">"Hello Vue!"</span></span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>你可以尝试调整js代码中<code>message</code>的值，页面上显示的内容也会随之改变。</p>
<p>想要了解更多关于Vue的内容，可以查看 <a href="https://cn.vuejs.org/v2/guide/" target="_blank" rel="noopener">官网教程</a>。</p>
<h3 id="1-2-Vue生命周期"><a href="#1-2-Vue生命周期" class="headerlink" title="1.2 Vue生命周期"></a>1.2 Vue生命周期</h3><p>java开发的同学都知道Servlet，Tomcat，Spring等技术或框架，他们都存在生命周期的概念。为什么会有生命周期的概念？原因是业务代码是被这些技术或框架调度执行的，而且调度器自身代码和业务代码一般会交叉执行；另外业务代码一般无法知晓调度器的状态变更，调度器就需要通过定义不同执行阶段，对外提供扩展点。</p>
<p>Vue也一样，它也是一个框架，因此也需要定义不同执行阶段，方便使用者扩展。</p>
<p>Vue的生命周期：</p>
<p><img src="https://cn.vuejs.org/images/lifecycle.png" alt></p>
<p>光看可能也无法有一个直观的感受，所以这里有一个简单的demo：</p>
<p><a href="https://codepen.io/jiangmitiao/pen/GRgvKXq" target="_blank" rel="noopener">在线演示</a></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">title</span>&gt;</span><span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"https://cdn.bootcss.com/vue/2.6.10/vue.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"app"</span>&gt;</span></span><br><span class="line">    &#123;&#123; message &#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">let</span> print = <span class="function"><span class="keyword">function</span>(<span class="params">vue, group</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.group(group);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.log(<span class="string">"el"</span>, vue.$el);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.log(<span class="string">"data"</span>, vue.$data);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.groupEnd();</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="actionscript"><span class="keyword">var</span> app = <span class="keyword">new</span> Vue(&#123;</span></span><br><span class="line"><span class="actionscript">  el: <span class="string">"#app"</span>,</span></span><br><span class="line">  data: &#123;</span><br><span class="line"><span class="actionscript">    message: <span class="string">"Hello Vue!"</span></span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeCreate() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"beforeCreate"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  created() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"created"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeMount() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"beforeMount"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  mounted() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"mounted"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeUpdate() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"beforeUpdate"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  updated() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"updated"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeDestroy() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"beforeDestroy"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  destroyed() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"destroyed"</span>);</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="javascript">setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.warn(<span class="string">"准备改变data数据"</span>);</span></span><br><span class="line"><span class="actionscript">  app.message = <span class="string">"this is my hello world"</span>;</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">  setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">    <span class="built_in">console</span>.warn(<span class="string">"准备销毁app"</span>);</span></span><br><span class="line">    app.$destroy();</span><br><span class="line"></span><br><span class="line"><span class="javascript">    setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">      <span class="built_in">console</span>.warn(<span class="string">"尝试再改变data数据"</span>);</span></span><br><span class="line"><span class="actionscript">      app.message = <span class="string">"is destroy?"</span>;</span></span><br><span class="line">    &#125;, 1000);</span><br><span class="line">  &#125;, 1000);</span><br><span class="line">&#125;, 1000);</span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>在这段代码中，我们在vue的不同阶段都执行打印方法，看看这些阶段的顺序是怎样的，并且是如何触发的。</p>
<h4 id="1-2-1-初始化阶段"><a href="#1-2-1-初始化阶段" class="headerlink" title="1.2.1 初始化阶段"></a>1.2.1 初始化阶段</h4><p>在js代码开始执行后，就会触发beforeCreate和created方法。在created阶段，vue会拿到指定data中的数据。</p>
<p><img src="/images/pasted-107.png" alt="upload successful"></p>
<h4 id="1-2-2-挂载阶段"><a href="#1-2-2-挂载阶段" class="headerlink" title="1.2.2 挂载阶段"></a>1.2.2 挂载阶段</h4><p>我们对着前面的生命周期图来看，可以看到，我们指定了el并且没有指定template。所以在beforeMount阶段会拿到el对应的html作为模板编译。之后，在mounted阶段，我们看到数据已经被渲染到el中。</p>
<p><img src="/images/pasted-108.png" alt="upload successful"></p>
<h4 id="1-2-3-更新阶段"><a href="#1-2-3-更新阶段" class="headerlink" title="1.2.3 更新阶段"></a>1.2.3 更新阶段</h4><p>当我们触发了data数据变更时，则会调用beforeUpdate和updated方法。</p>
<p><img src="/images/pasted-109.png" alt="upload successful"></p>
<h4 id="1-2-4-销毁阶段"><a href="#1-2-4-销毁阶段" class="headerlink" title="1.2.4 销毁阶段"></a>1.2.4 销毁阶段</h4><p>当我们调用vue的销毁方法时，则会触发beforeDestroy和destroyed方法。并且在destroy之后，不会再响应data数据的变更。</p>
<p><img src="/images/pasted-110.png" alt="upload successful"></p>
<h4 id="1-2-5-小结"><a href="#1-2-5-小结" class="headerlink" title="1.2.5 小结"></a>1.2.5 小结</h4><p>已上，我们简单的过了一下vue的生命周期。由于本位重点不在el和template上，更多有关生命周期的内容可以参考这篇文章 <a href="https://www.cnblogs.com/wangjiachen666/p/9497749.html" target="_blank" rel="noopener">通俗易懂了解Vue组件的生命周期</a> 。</p>
<h3 id="1-3-Vue组件介绍"><a href="#1-3-Vue组件介绍" class="headerlink" title="1.3 Vue组件介绍"></a>1.3 Vue组件介绍</h3><p>了解完Vue的生命周期，我们再来看看Vue组件。什么是Vue组件？你可以理解为Java中的Class。之前咱们写的Vue实例就是Java中直接写main方法，不牵扯类和对象。而Vue组件就是Class类，你可以在main方法中new出不同的Class实例。</p>
<p>来看看这段代码：</p>
<p><a href="https://codepen.io/jiangmitiao/pen/yLyoLYR" target="_blank" rel="noopener">在线演示</a></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">title</span>&gt;</span><span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"https://cdn.bootcss.com/vue/2.6.10/vue.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"app"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123; message &#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">cp1</span>&gt;</span><span class="tag">&lt;/<span class="name">cp1</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">let</span> print = <span class="function"><span class="keyword">function</span>(<span class="params">vue, group</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.group(group);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.log(<span class="string">"el"</span>, vue.$el);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.log(<span class="string">"data"</span>, vue.$data);</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.groupEnd();</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="actionscript"><span class="comment">// 全局注册一个组件</span></span></span><br><span class="line"><span class="actionscript">Vue.component(<span class="string">"cp1"</span>, &#123;</span></span><br><span class="line"><span class="actionscript">  data: <span class="function"><span class="keyword">function</span><span class="params">()</span> </span>&#123;</span></span><br><span class="line"><span class="actionscript">    <span class="keyword">return</span> &#123;</span></span><br><span class="line"><span class="actionscript">      name: <span class="string">"CP1"</span></span></span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;,</span><br><span class="line"><span class="handlebars"><span class="xml">  template: "<span class="tag">&lt;<span class="name">p</span>&gt;</span></span><span class="template-variable">&#123;&#123; name &#125;&#125;</span><span class="xml"><span class="tag">&lt;/<span class="name">p</span>&gt;</span>",</span></span></span><br><span class="line">  beforeCreate() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"cp1 beforeCreate"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  created() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"cp1 created"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeMount() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"cp1 beforeMount"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  mounted() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"cp1 mounted"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeUpdate() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"cp1 beforeUpdate"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  updated() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"cp1 updated"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeDestroy() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"cp1 beforeDestroy"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  destroyed() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"cp1 destroyed"</span>);</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="actionscript"><span class="keyword">var</span> app = <span class="keyword">new</span> Vue(&#123;</span></span><br><span class="line"><span class="actionscript">  el: <span class="string">"#app"</span>,</span></span><br><span class="line">  data: &#123;</span><br><span class="line"><span class="actionscript">    message: <span class="string">"Hello Vue!"</span></span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeCreate() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"beforeCreate"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  created() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"created"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeMount() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"beforeMount"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  mounted() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"mounted"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeUpdate() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"beforeUpdate"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  updated() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"updated"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line">  beforeDestroy() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"beforeDestroy"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  destroyed() &#123;</span><br><span class="line"><span class="actionscript">    print(<span class="keyword">this</span>, <span class="string">"destroyed"</span>);</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="javascript">setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">  <span class="built_in">console</span>.warn(<span class="string">"准备改变data数据"</span>);</span></span><br><span class="line"><span class="actionscript">  app.message = <span class="string">"this is my hello world"</span>;</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">  setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">    <span class="built_in">console</span>.warn(<span class="string">"准备销毁app"</span>);</span></span><br><span class="line">    app.$destroy();</span><br><span class="line"></span><br><span class="line"><span class="javascript">    setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">      <span class="built_in">console</span>.warn(<span class="string">"尝试再改变data数据"</span>);</span></span><br><span class="line"><span class="actionscript">      app.message = <span class="string">"is destroy?"</span>;</span></span><br><span class="line">    &#125;, 1000);</span><br><span class="line">  &#125;, 1000);</span><br><span class="line">&#125;, 1000);</span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>在这段代码中，我们注册了一个叫cp1的组件。注册组件需要注意一个事情，就是data返回的必须是个函数，原因是组件可以实例化很多个，多个组件实例之间data数据是要隔离的。另外还需要设置template。</p>
<p>执行完这段代码，可以看到组件在父实例beforeMount之前会先mount，在父实例beforeDestroy之前会先destroy。</p>
<p>如果想要了解更多有关Vue实例的知识，可以查看 <a href="https://cn.vuejs.org/v2/guide/components-registration.html" target="_blank" rel="noopener">官网:深入了解组件</a>。</p>
<h2 id="2-前端路由化开发"><a href="#2-前端路由化开发" class="headerlink" title="2. 前端路由化开发"></a>2. 前端路由化开发</h2><h3 id="2-1-前端路由是什么"><a href="#2-1-前端路由是什么" class="headerlink" title="2.1 前端路由是什么"></a>2.1 前端路由是什么</h3><p>路由这个词大家应该都听说过（除非你没用过路由器），那么在一个管理系统中也有路由一说，例如在springmvc中通过不同的uri选择不同的controller生成不同的view。</p>
<p>而前端路由又从何说起？最开始的互联网大多数网页都是直接返回html代码，用户每次交互都是需要跳转刷新页面，整个操作体感不是很好。随着互联网的发展，1996年微软提出iframe标签，从而带来了异步加载和请求元素的概念。在1998年，微软提出了Ajax（ Asynchronous JavaScript And XML）的基本概念（XMLHttpRequest的前身）。最终大多数浏览器都提供了XMLHttpRequest的实现。</p>
<p>在有了异步加载技术方案Ajax后，我们发现一个系统可以只有一个页面，通过响应用户的交互，异步加载相关数据并展示在前台。这样，访问这个系统就像是在使用一个本地软件。</p>
<p>这个时候问题来了，当用户噼里啪啦做了一堆查询筛选后，我们的确也给用户展示了相关数据。可用户想把这个网页收藏起来供下次直接访问，或者发送给别人看。问题就出现了，由于一个url对应着一个前端单页，每次用户打开这个url，看到的都是最初的页面，而不是经过噼里啪啦筛选后的页面。</p>
<p>怎么办呢？URL协议的组成部分中有一个hash（锚），修改锚并不会向后端发起请求。所以做前端的同学就开始利用这个锚，把用户的筛选项保存在这个锚上，每当用户打开带有锚的url，js就能根据锚来还原最初用户所做的筛选。</p>
<p>2014年以后，HTML5提供了HistoryAPI，也可以实现路由的功能。</p>
<p><a href="https://www.zhihu.com/question/53064386" target="_blank" rel="noopener">前端路由是什么东西</a></p>
<p><a href="https://zhuanlan.zhihu.com/p/61694291" target="_blank" rel="noopener">前端路由的基本原理</a></p>
<h3 id="2-2-VueRouter介绍"><a href="#2-2-VueRouter介绍" class="headerlink" title="2.2 VueRouter介绍"></a>2.2 VueRouter介绍</h3><p>VueRouter是Vue的核心插件，是官方指定的路由管理器，它和Vue深度集成。</p>
<p>这里我们来演示一下VueRouter的简单使用：</p>
<p><a href="https://codepen.io/jiangmitiao/pen/povroyx" target="_blank" rel="noopener">在线演示</a></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">title</span>&gt;</span><span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"https://cdn.bootcss.com/vue/2.6.10/vue.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"https://cdn.bootcss.com/vue-router/3.1.3/vue-router.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"app"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123; message &#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span></span><br><span class="line">      <span class="comment">&lt;!-- 使用 router-link 组件来导航. --&gt;</span></span><br><span class="line">      <span class="comment">&lt;!-- 通过传入 `to` 属性指定链接. --&gt;</span></span><br><span class="line">      <span class="comment">&lt;!-- &lt;router-link&gt; 默认会被渲染成一个 `&lt;a&gt;` 标签 --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">router-link</span> <span class="attr">to</span>=<span class="string">"/cp1"</span>&gt;</span>Go to CP1<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">router-link</span> <span class="attr">to</span>=<span class="string">"/cp2"</span>&gt;</span>Go to CP2<span class="tag">&lt;/<span class="name">router-link</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 路由出口 --&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 路由匹配到的组件将渲染在这里 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">router-view</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript"><span class="comment">// cp1组件</span></span></span><br><span class="line"><span class="actionscript"><span class="keyword">const</span> cp1 = &#123;</span></span><br><span class="line"><span class="actionscript">  data: <span class="function"><span class="keyword">function</span><span class="params">()</span> </span>&#123;</span></span><br><span class="line"><span class="actionscript">    <span class="keyword">return</span> &#123;</span></span><br><span class="line"><span class="actionscript">      name: <span class="string">"CP1"</span></span></span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;,</span><br><span class="line">  mounted() &#123;</span><br><span class="line"><span class="javascript">    <span class="built_in">console</span>.log(<span class="string">"cp1 mounted"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  destroyed() &#123;</span><br><span class="line"><span class="javascript">    <span class="built_in">console</span>.log(<span class="string">"cp1 destroyed"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line"><span class="handlebars"><span class="xml">  template: "<span class="tag">&lt;<span class="name">p</span>&gt;</span></span><span class="template-variable">&#123;&#123; name &#125;&#125;</span><span class="xml"><span class="tag">&lt;/<span class="name">p</span>&gt;</span>"</span></span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="actionscript"><span class="comment">// cp2组件</span></span></span><br><span class="line"><span class="actionscript"><span class="keyword">const</span> cp2 = &#123;</span></span><br><span class="line"><span class="actionscript">  data: <span class="function"><span class="keyword">function</span><span class="params">()</span> </span>&#123;</span></span><br><span class="line"><span class="actionscript">    <span class="keyword">return</span> &#123;</span></span><br><span class="line"><span class="actionscript">      name: <span class="string">"CP2"</span></span></span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;,</span><br><span class="line">  mounted() &#123;</span><br><span class="line"><span class="javascript">    <span class="built_in">console</span>.log(<span class="string">"cp2 mounted"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  destroyed() &#123;</span><br><span class="line"><span class="javascript">    <span class="built_in">console</span>.log(<span class="string">"cp2 destroyed"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line"><span class="handlebars"><span class="xml">  template: "<span class="tag">&lt;<span class="name">p</span>&gt;</span></span><span class="template-variable">&#123;&#123; name &#125;&#125;</span><span class="xml"><span class="tag">&lt;/<span class="name">p</span>&gt;</span>"</span></span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="actionscript"><span class="comment">// 指定路由</span></span></span><br><span class="line"><span class="actionscript"><span class="keyword">const</span> routes = [</span></span><br><span class="line">  &#123;</span><br><span class="line"><span class="actionscript">    path: <span class="string">"/cp1"</span>,</span></span><br><span class="line">    component: cp1</span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line"><span class="actionscript">    path: <span class="string">"/cp2"</span>,</span></span><br><span class="line">    component: cp2</span><br><span class="line">  &#125;</span><br><span class="line">];</span><br><span class="line"></span><br><span class="line"><span class="actionscript"><span class="comment">// 生成VueRouter实例</span></span></span><br><span class="line"><span class="actionscript"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123; routes: routes &#125;);</span></span><br><span class="line"></span><br><span class="line"><span class="actionscript"><span class="comment">// 在vue中加载vuerouter</span></span></span><br><span class="line"><span class="actionscript"><span class="keyword">var</span> app = <span class="keyword">new</span> Vue(&#123;</span></span><br><span class="line">  router: router,</span><br><span class="line"><span class="actionscript">  el: <span class="string">"#app"</span>,</span></span><br><span class="line">  data: &#123;</span><br><span class="line"><span class="actionscript">    message: <span class="string">"Hello Vue!"</span></span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>如果你在本地运行代码，分别点击两个a标签会发现分别有<code>CP1</code>和<code>CP2</code>出现在页面上，并且浏览器的地址栏中url的锚部分也会变成<code>/cp1</code>和<code>cp2</code>。</p>
<p><img src="/images/pasted-111.png" alt="upload successful"></p>
<p>可以这么说，当你了解了前端路由的原理，你也可以实现一个你的路由框架。只不过VueRouter是一个完备地、稳定地路由框架，所以直接用它就可以了。</p>
<p>想要了解更多有关VueRouter的知识，可以查看 <a href="https://router.vuejs.org/zh/guide/" target="_blank" rel="noopener">官方文档</a></p>
<h3 id="2-3-Vue路由使用技巧"><a href="#2-3-Vue路由使用技巧" class="headerlink" title="2.3 Vue路由使用技巧"></a>2.3 Vue路由使用技巧</h3><p>前面2.2节，我们演示了最简单的Vue路由功能。而实际上，要实现2.1节中所说的打开带有锚的页面、自动填充筛选项、查询并渲染数据，还是需要一定的技巧。这里，我来总结一下结合Vue的生命周期，如何实现页面的生命周期管理。</p>
<p><img src="/images/pasted-112.png" alt="upload successful"></p>
<p>如图，当用户发送request，打开页面时，vue会回调created方法。在created方法中，调用自己写的init方法，在init方法中，先将路由查询参数填充到自身data中，然后调用自己写的fetchData方法。在自己写的fetchData方法中，用data中的数据作为参数请求后台，拿到数据后填充到自身data中。vue会自动渲染数据，而当vue监听到select/input/click事件后，调用自己写的parameterChanged方法，在该方法中，push一个新的路由，其中参数是用户新筛选的。最后，使用Vue的监听功能，监听route变化，当route变化后，触发init方法。</p>
<p>已上整个流程，将实现2.1节中所说的用户打开带有锚的页面、自动填充筛选项、查询并渲染数据，同时当用户筛选发生变化时，可以及时调整路由（锚）。</p>
<p>以下是一个简单的实现：</p>
<p><a href="https://codepen.io/jiangmitiao/pen/KKwvKqr" target="_blank" rel="noopener">在线演示</a></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">title</span>&gt;</span><span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"https://cdn.bootcss.com/vue/2.6.10/vue.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"https://cdn.bootcss.com/vue-router/3.1.3/vue-router.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"app"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123; message &#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span></span><br><span class="line">      <span class="comment">&lt;!-- 使用 router-link 组件来导航. --&gt;</span></span><br><span class="line">      <span class="comment">&lt;!-- 通过传入 `to` 属性指定链接. --&gt;</span></span><br><span class="line">      <span class="comment">&lt;!-- &lt;router-link&gt; 默认会被渲染成一个 `&lt;a&gt;` 标签 --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">a</span> @<span class="attr">click</span>=<span class="string">"$router.push(&#123;</span></span></span><br><span class="line"><span class="tag"><span class="string">                  path:'/cp1',</span></span></span><br><span class="line"><span class="tag"><span class="string">                    query: &#123;p1:1,p2:2,t:+new Date()&#125;</span></span></span><br><span class="line"><span class="tag"><span class="string">                &#125;)"</span></span></span><br><span class="line"><span class="tag">         &gt;</span>TO CP1<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">a</span> @<span class="attr">click</span>=<span class="string">"$router.push(&#123;</span></span></span><br><span class="line"><span class="tag"><span class="string">                  path:'/cp2',</span></span></span><br><span class="line"><span class="tag"><span class="string">                    query: &#123;p1:3,p2:4,t:+new Date()&#125;</span></span></span><br><span class="line"><span class="tag"><span class="string">                &#125;)"</span></span></span><br><span class="line"><span class="tag">         &gt;</span>TO CP2<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 路由出口 --&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 路由匹配到的组件将渲染在这里 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">router-view</span>&gt;</span><span class="tag">&lt;/<span class="name">router-view</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="actionscript"><span class="comment">// cp1组件</span></span></span><br><span class="line"><span class="actionscript"><span class="keyword">const</span> cp1 = &#123;</span></span><br><span class="line"><span class="actionscript">  data: <span class="function"><span class="keyword">function</span><span class="params">()</span> </span>&#123;</span></span><br><span class="line"><span class="actionscript">    <span class="keyword">return</span> &#123;</span></span><br><span class="line"><span class="actionscript">      name: <span class="string">"CP1"</span></span></span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;,</span><br><span class="line">  watch: &#123;</span><br><span class="line"><span class="actionscript">    $route: <span class="string">"init"</span></span></span><br><span class="line">  &#125;,</span><br><span class="line">  methods: &#123;</span><br><span class="line">    init() &#123;</span><br><span class="line"><span class="javascript">      <span class="built_in">console</span>.log(<span class="string">"cp1.init 在这里获取前端路由参数,并根据路由参数查询后台数据"</span>,<span class="keyword">this</span>.$route.query);</span></span><br><span class="line"><span class="actionscript">      <span class="comment">//拿到路由参数，并填充到自身的data中</span></span></span><br><span class="line"><span class="actionscript">      <span class="comment">//调用query方法</span></span></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.query();</span></span><br><span class="line">    &#125;,</span><br><span class="line">    query()&#123;</span><br><span class="line"><span class="actionscript">      <span class="comment">// 拿到data中的数据，获取后台数据，并填充到自身data中</span></span></span><br><span class="line"><span class="javascript">      <span class="keyword">this</span>.name = <span class="string">"CP1"</span>+<span class="built_in">JSON</span>.stringify(<span class="keyword">this</span>.$route.query);</span></span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  created() &#123;</span><br><span class="line"><span class="javascript">    <span class="built_in">console</span>.log(<span class="string">"cp1 created"</span>);</span></span><br><span class="line"><span class="actionscript">    <span class="keyword">this</span>.init();</span></span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  destroyed() &#123;</span><br><span class="line"><span class="javascript">    <span class="built_in">console</span>.log(<span class="string">"cp1 destroyed"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line"><span class="handlebars"><span class="xml">  template: "<span class="tag">&lt;<span class="name">p</span>&gt;</span></span><span class="template-variable">&#123;&#123; name &#125;&#125;</span><span class="xml"><span class="tag">&lt;/<span class="name">p</span>&gt;</span>"</span></span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="actionscript"><span class="comment">// cp2组件</span></span></span><br><span class="line"><span class="actionscript"><span class="keyword">const</span> cp2 = &#123;</span></span><br><span class="line"><span class="actionscript">  data: <span class="function"><span class="keyword">function</span><span class="params">()</span> </span>&#123;</span></span><br><span class="line"><span class="actionscript">    <span class="keyword">return</span> &#123;</span></span><br><span class="line"><span class="actionscript">      name: <span class="string">"CP2"</span></span></span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;,</span><br><span class="line">  watch: &#123;</span><br><span class="line"><span class="actionscript">    $route: <span class="string">"init"</span></span></span><br><span class="line">  &#125;,</span><br><span class="line">  methods: &#123;</span><br><span class="line">    init() &#123;</span><br><span class="line"><span class="javascript">      <span class="built_in">console</span>.log(<span class="string">"cp2.init 在这里获取前端路由参数,并根据路由参数查询后台数据"</span>,<span class="keyword">this</span>.$route.query);</span></span><br><span class="line"><span class="actionscript">    <span class="comment">//拿到路由参数，并填充到自身的data中</span></span></span><br><span class="line"><span class="actionscript">      <span class="comment">//调用query方法</span></span></span><br><span class="line"><span class="actionscript">      <span class="keyword">this</span>.query()</span></span><br><span class="line">    &#125;,</span><br><span class="line">    query()&#123;</span><br><span class="line"><span class="actionscript">      <span class="comment">// 拿到data中的数据，获取后台数据，并填充到自身data中</span></span></span><br><span class="line"><span class="javascript">      <span class="keyword">this</span>.name = <span class="string">"CP2"</span>+<span class="built_in">JSON</span>.stringify(<span class="keyword">this</span>.$route.query);</span></span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  created() &#123;</span><br><span class="line"><span class="javascript">    <span class="built_in">console</span>.log(<span class="string">"cp2 created"</span>);</span></span><br><span class="line"><span class="actionscript">    <span class="keyword">this</span>.init();</span></span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  destroyed() &#123;</span><br><span class="line"><span class="javascript">    <span class="built_in">console</span>.log(<span class="string">"cp2 destroyed"</span>);</span></span><br><span class="line">  &#125;,</span><br><span class="line"><span class="handlebars"><span class="xml">  template: "<span class="tag">&lt;<span class="name">p</span>&gt;</span></span><span class="template-variable">&#123;&#123; name &#125;&#125;</span><span class="xml"><span class="tag">&lt;/<span class="name">p</span>&gt;</span>"</span></span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="actionscript"><span class="comment">// 指定路由</span></span></span><br><span class="line"><span class="actionscript"><span class="keyword">const</span> routes = [</span></span><br><span class="line">  &#123;</span><br><span class="line"><span class="actionscript">    path: <span class="string">"/cp1"</span>,</span></span><br><span class="line">    component: cp1</span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;</span><br><span class="line"><span class="actionscript">    path: <span class="string">"/cp2"</span>,</span></span><br><span class="line">    component: cp2</span><br><span class="line">  &#125;</span><br><span class="line">];</span><br><span class="line"><span class="actionscript"><span class="comment">// 生成VueRouter实例</span></span></span><br><span class="line"><span class="actionscript"><span class="keyword">const</span> router = <span class="keyword">new</span> VueRouter(&#123; routes: routes &#125;);</span></span><br><span class="line"><span class="actionscript"><span class="comment">// 在vue中加载vuerouter</span></span></span><br><span class="line"><span class="actionscript"><span class="keyword">var</span> app = <span class="keyword">new</span> Vue(&#123;</span></span><br><span class="line">  router: router,</span><br><span class="line"><span class="actionscript">  el: <span class="string">"#app"</span>,</span></span><br><span class="line">  data: &#123;</span><br><span class="line"><span class="actionscript">    message: <span class="string">"Hello Vue!"</span></span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>先点击CP1，再点击CP2的效果：<br><img src="/images/pasted-113.png" alt="upload successful"></p>
<p>打开带锚url后的效果：</p>
<p><img src="/images/pasted-114.png" alt="upload successful"></p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>Vue和它的插件Vue-Router能够帮助我们快速实现数据渲染和单页开发。不过，对于不熟悉Vue的同学，快速搭建还有有一定难度。希望通过以上的讲解，能够帮助大家更快的入门Vue前端开发。</p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Gavin Zhang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.gavinzh.com/2020/01/05/Vue-lifecycle-and-front-end-routing-usage/" title="Vue的生命周期和前端路由使用">http://blog.gavinzh.com/2020/01/05/Vue-lifecycle-and-front-end-routing-usage/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/javascript/" rel="tag"># javascript</a>
          
            <a href="/tags/vue/" rel="tag"># vue</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/01/05/some-thoutgths-when-upgrade-spring/" rel="next" title="SpringBoot 1.X到2.X 升级的一些思考总结">
                <i class="fa fa-chevron-left"></i> SpringBoot 1.X到2.X 升级的一些思考总结
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/03/20/Reverse-Polish-notation-Implement-with-java/" rel="prev" title="逆波兰式的java实现与计算">
                逆波兰式的java实现与计算 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://avatars3.githubusercontent.com/u/5567916" alt="Gavin Zhang">
            
              <p class="site-author-name" itemprop="name">Gavin Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">158</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/jiangmitiao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:me at gavinzh.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#0-前言"><span class="nav-number">1.</span> <span class="nav-text">0. 前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-Vue的生命周期"><span class="nav-number">2.</span> <span class="nav-text">1. Vue的生命周期</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-Vue是什么"><span class="nav-number">2.1.</span> <span class="nav-text">1.1 Vue是什么</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-Vue生命周期"><span class="nav-number">2.2.</span> <span class="nav-text">1.2 Vue生命周期</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-1-初始化阶段"><span class="nav-number">2.2.1.</span> <span class="nav-text">1.2.1 初始化阶段</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-2-挂载阶段"><span class="nav-number">2.2.2.</span> <span class="nav-text">1.2.2 挂载阶段</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-3-更新阶段"><span class="nav-number">2.2.3.</span> <span class="nav-text">1.2.3 更新阶段</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-4-销毁阶段"><span class="nav-number">2.2.4.</span> <span class="nav-text">1.2.4 销毁阶段</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-5-小结"><span class="nav-number">2.2.5.</span> <span class="nav-text">1.2.5 小结</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-Vue组件介绍"><span class="nav-number">2.3.</span> <span class="nav-text">1.3 Vue组件介绍</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-前端路由化开发"><span class="nav-number">3.</span> <span class="nav-text">2. 前端路由化开发</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-前端路由是什么"><span class="nav-number">3.1.</span> <span class="nav-text">2.1 前端路由是什么</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-VueRouter介绍"><span class="nav-number">3.2.</span> <span class="nav-text">2.2 VueRouter介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-Vue路由使用技巧"><span class="nav-number">3.3.</span> <span class="nav-text">2.3 Vue路由使用技巧</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2013 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gavin Zhang</span>

  

  
</div>





<div>
	<a href="http://www.beian.miit.gov.cn/" target="_blank">陕ICP备17010002号-1</a>
</div>





        




  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=61868582";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1261805793&web_id=1261805793" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>





  



  






  













  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fastclick/1.0.6/fastclick.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.0"></script>



  


  

    
      <script id="dsq-count-scr" src="https://zhang-hengs-website-blog.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://blog.gavinzh.com/2020/01/05/Vue-lifecycle-and-front-end-routing-usage/';
          this.page.identifier = '2020/01/05/Vue-lifecycle-and-front-end-routing-usage/';
          this.page.title = 'Vue的生命周期和前端路由使用';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://zhang-hengs-website-blog.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("EhAMmIXTRGtethTcgYwA9afH-gzGzoHsz", "jzP1TaBhMleAUgPLXyB0h8oQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=6.0.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=6.0.0"></script>


  

</body>
</html>
